<template>
    <el-select
        v-model="data"
        filterable
        remote
        clearable
        reserve-keyword
        :remote-method="remoteMethod"
        :loading="selectLoading"
        loading-text="正在加载中..."
        :popper-append-to-body="false"
        :teleported="false"
        placeholder="请输入"
        class="form-input select"
        @change="onChange"
        @clear="onClear"
    >
        <template #prefix>
            <span class="label">{{ label }}</span>
        </template>
        <el-option
            v-for="item in list"
            :key="item[basicInfo.value]"
            :label="item[basicInfo.label]"
            :value="item[basicInfo.value]"
        />
    </el-select>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, computed, defineExpose, watchEffect } from 'vue';
import { getCustomerList, getUserList } from '@/api/delivery/customerManage';
import { useStore } from 'vuex';

// 加盟商编码（登录时已保存）
const store = useStore();

const emit = defineEmits(['onChange']);

const list: any = ref([]);

const groupCodeRef = computed(() => store.state.userGroup.groupCode || '');
const data = ref('');

const props = defineProps({
    label: {
        type: String,
        default: '',
    },
    basicInfo: {
        type: Object,
        default: () => {
            return {
                value: 'customerId',
                label: 'company',
            };
        },
    },
    queryType: {
        type: String,
        default: '1',
    },
    targetData: {
        type: String,
        default: '',
    },
});

const selectLoading = ref(false);

const remoteMethod = async (query: string) => {
    if (query) {
        selectLoading.value = true;
        try {
            let data = null;
            if (props.queryType === '2') {
                data = await getUserList({ departCode: groupCodeRef.value, name: query });
            } else {
                data = await getCustomerList({ joinTraderCode: groupCodeRef.value, company: query });
            }
            list.value = data.list;
        } finally {
            selectLoading.value = false;
        }
    }
};

const onChange = (val: string) => {
    emit('onChange', val);
};

const onClear = () => {
    data.value = '';
    list.value = [];
    emit('onChange', '');
};

watchEffect(() => {
    if (props.targetData) {
        data.value = props.targetData;
    }
});

// 对外暴露可执行方法
defineExpose({
    onClear,
});
</script>

<style lang="scss" scoped></style>
